package com.wanma.thread.threaddemo2;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 使用lock锁
 * 
 * @author Administrator
 *
 */
public class ThreadDemo1 {
	/*
	 * 数据错乱
	 */
	public static void main(String[] args) {
		
		Res res = new Res();
		InpThread InpThread = new InpThread(res);
		ReadThread ReadThread = new ReadThread(res);
		InpThread.start();
		ReadThread.start();
	}
	
}
class  Res{
	 String name;
  	 String sex;
  	 Lock lock = new ReentrantLock();
	 public boolean flag = false;
	 Condition condition = lock.newCondition();
}
//写入线程
class InpThread extends Thread{
	private Res res;
	public InpThread(Res res) {
		this.res = res;
	}
	@Override
	public void run() {
		int count = 0;
		while (true) {
			res.lock.lock();
				if(res.flag){
					try {
						res.condition.await();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					//try {
						//res.wait();
					//} catch (InterruptedException e) {
					//	e.printStackTrace();
					//}
				}
				if(count == 0){
					res.name = "余胜军";
					res.sex = "男";
				}else{
					res.name = "小红";
					res.sex = "女";
				}
				count = (count+1) %2;
				res.flag = true;
			//	res.notify();
				
				res.condition.signal();
				res.lock.unlock();
		}
	}
}
//读取线程
class ReadThread extends Thread{
	private Res res;
	public ReadThread(Res res) {
		this.res = res;
	}
	@Override
	public void run() {
		while(true){
			//synchronized(res){
			res.lock.lock();
				if(!res.flag){
					try {
						res.condition.await();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
//					try {
//						res.wait();
//					} catch (InterruptedException e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					}
				}
				System.out.println(res.name + "---/t"+ res.sex);
				res.flag = false;
				//res.notify();
				
				res.condition.signal();
				res.lock.unlock();
			}
		//}
	}
}
